import 'package:flutter/material.dart';

enum DropDownAlignment {
  left,
  right,
  center,
}

enum DropDownMainAxisAlignment {
  start,
  end,
  center,
  spaceBetween,
  spaceAround,
  spaceEvenly,
}

class DropDownDevicePicker extends StatefulWidget {
  /// 主标题文本
  final String title;
  /// 箭头图标（可自定义样式）
  final Widget arrowIcon;
  /// 设备列表数据
  final List<String> deviceList;
  /// 主容器背景色
  final Color mainContainerColor;
  /// 下拉菜单背景色
  final Color dropdownBackgroundColor;
  /// 主容器边框颜色
  final Color borderColor;
  /// 下拉菜单边框颜色
  final Color dropdownBorderColor;
  /// 选中项打勾图标
  final Widget checkIcon;
  /// 主容器宽度
  final double width;
  /// 主容器高度
  final double height;
  /// 下拉菜单对齐方式
  final DropDownAlignment dropdownAlignment;
  /// 主容器内标题和箭头的对齐方式
  final DropDownMainAxisAlignment alignment;
  /// 标题内边距（控制标题与容器边缘的间距）
  final EdgeInsetsGeometry titlePadding;
  /// 选中回调
  final ValueChanged<String>? onSelected;
  /// 边框圆角
  final double borderRadius;
  /// 主容器内边距
  final EdgeInsetsGeometry padding;
  /// 下拉菜单最大高度
  final double maxDropdownHeight;
  /// 下拉菜单宽度
  final double dropdownWidth;
  /// 主容器边框宽度
  final double borderWidth;
  /// 下拉菜单边框宽度
  final double dropdownBorderWidth;
  /// 主容器阴影
  final List<BoxShadow>? boxShadow;
  /// 下拉菜单阴影
  final List<BoxShadow>? dropdownBoxShadow;
  /// 标题文本样式
  final TextStyle? titleStyle;
  /// 列表项文本样式
  final TextStyle? itemStyle;
  /// 选中项文本样式
  final TextStyle? selectedItemStyle;
  /// 下拉菜单尖角大小
  final double triangleSize;
  /// 下拉菜单尖角颜色
  final Color triangleColor;
  /// 三角形在下拉菜单顶部边框的位置（0-100，0表示最左边，100表示最右边）
  final double trianglePosition;
  /// 选中图标区域的宽度
  final double checkIconWidth;
  /// 列表项内容的内边距，控制列表项整体的位置
  final EdgeInsetsGeometry itemPadding;
  /// 下拉菜单相对于页面宽度的定位百分比 (0.0-100.0)
  /// 0表示左对齐，100表示右对齐，50表示居中
  final double pagePositionPercent;
  /// 是否忽略页面安全区域
  final bool ignoreSafeArea;
  /// 新增：判断选项是否被选中的回调
  final bool Function(String)? isSelected;

  const DropDownDevicePicker({
    super.key,
    required this.title,
    required this.arrowIcon,
    required this.deviceList,
    this.mainContainerColor = Colors.white,
    this.dropdownBackgroundColor = Colors.white,
    this.borderColor = Colors.grey,
    this.dropdownBorderColor = Colors.grey,
    this.checkIcon = const Icon(Icons.check, size: 20),
    this.width = 200,
    this.height = 44,
    this.dropdownAlignment = DropDownAlignment.left,
    this.alignment = DropDownMainAxisAlignment.spaceBetween,
    this.titlePadding = EdgeInsets.zero,
    this.onSelected,
    this.borderRadius = 8.0,
    this.padding = const EdgeInsets.symmetric(horizontal: 12),
    this.maxDropdownHeight = 200,
    this.dropdownWidth = 160,
    this.borderWidth = 1.0,
    this.dropdownBorderWidth = 1.0,
    this.boxShadow,
    this.dropdownBoxShadow,
    this.titleStyle,
    this.itemStyle,
    this.selectedItemStyle,
    this.triangleSize = 10.0,
    this.triangleColor = Colors.white,
    this.trianglePosition = 80.0,
    this.checkIconWidth = 20.0,
    this.itemPadding = const EdgeInsets.only(left: 8.0, right: 16.0),
    this.pagePositionPercent = 0.0, // 默认左对齐
    this.ignoreSafeArea = false,   // 默认不忽略安全区域
    this.isSelected, // 新增参数
  });

  @override
  State<DropDownDevicePicker> createState() => _DropDownDevicePickerState();
}

class _DropDownDevicePickerState extends State<DropDownDevicePicker> {
  // 移除内部维护的选中状态，改为使用外部传入的isSelected回调
  // String? _selectedDevice;
  OverlayEntry? _overlayEntry;
  final LayerLink _layerLink = LayerLink();

  MainAxisAlignment _getMainAxisAlignment() {
    switch (widget.alignment) {
      case DropDownMainAxisAlignment.start:
        return MainAxisAlignment.start;
      case DropDownMainAxisAlignment.end:
        return MainAxisAlignment.end;
      case DropDownMainAxisAlignment.center:
        return MainAxisAlignment.center;
      case DropDownMainAxisAlignment.spaceBetween:
        return MainAxisAlignment.spaceBetween;
      case DropDownMainAxisAlignment.spaceAround:
        return MainAxisAlignment.spaceAround;
      case DropDownMainAxisAlignment.spaceEvenly:
        return MainAxisAlignment.spaceEvenly;
    }
  }

  @override
  void dispose() {
    _removeOverlay();
    super.dispose();
  }

  void _showOverlay() {
    _removeOverlay();

    final RenderBox renderBox = context.findRenderObject() as RenderBox;
    final Size size = renderBox.size;
    final Offset offset = renderBox.localToGlobal(Offset.zero);

    // 获取屏幕尺寸
    final mediaQuery = MediaQuery.of(context);
    final screenWidth = mediaQuery.size.width;

    // 考虑安全区域
    double safeAreaLeft = 0;
    double safeAreaRight = 0;
    if (!widget.ignoreSafeArea) {
      safeAreaLeft = mediaQuery.padding.left;
      safeAreaRight = mediaQuery.padding.right;
    }

    final availableWidth = screenWidth - safeAreaLeft - safeAreaRight;
    final safeAreaOffset = safeAreaLeft;

    // 警告用户不要同时使用pagePositionPercent和dropdownAlignment
    if (widget.pagePositionPercent != 0.0 &&
        widget.dropdownAlignment != DropDownAlignment.left) {
      debugPrint('''
警告: DropDownDevicePicker同时设置了pagePositionPercent和dropdownAlignment。
pagePositionPercent将覆盖dropdownAlignment的设置。建议只使用其中一个属性来控制下拉菜单的位置。
''');
    }

    // 基于页面百分比计算下拉菜单位置（优先使用pagePositionPercent）
    double left = safeAreaOffset +
        (availableWidth - widget.dropdownWidth) *
            (widget.pagePositionPercent.clamp(0.0, 100.0) / 100.0);

    // 如果pagePositionPercent为默认值0，则使用dropdownAlignment作为后备
    if (widget.pagePositionPercent == 0.0) {
      switch (widget.dropdownAlignment) {
        case DropDownAlignment.left:
          left = offset.dx;
          break;
        case DropDownAlignment.right:
          left = offset.dx + size.width - widget.dropdownWidth;
          break;
        case DropDownAlignment.center:
          left = offset.dx + (size.width - widget.dropdownWidth) / 2;
          break;
      }
    }

    // 计算三角形的水平位置（基于百分比）
    double triangleHorizontalOffset = (widget.dropdownWidth - widget.triangleSize * 2) *
        (widget.trianglePosition.clamp(0.0, 100.0) / 100.0);

    _overlayEntry = OverlayEntry(
      builder: (BuildContext context) {
        return Positioned(
          left: left,
          top: offset.dy + size.height + 4,
          width: widget.dropdownWidth,
          child: CompositedTransformFollower(
            link: _layerLink,
            showWhenUnlinked: false,
            offset: Offset(0.0, size.height + 4),
            child: Container(
              color: Colors.transparent,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 调整三角形位置，使其与下拉菜单顶部无缝连接
                  Padding(
                    padding: EdgeInsets.only(left: triangleHorizontalOffset),
                    child: CustomPaint(
                      size: Size(widget.triangleSize * 2, widget.triangleSize),
                      painter: TrianglePainter(
                        color: widget.dropdownBackgroundColor,
                        borderColor: widget.dropdownBorderColor,
                        borderWidth: widget.dropdownBorderWidth,
                        drawBottomBorder: false, // 不绘制三角形底部边框
                      ),
                    ),
                  ),
                  // 移除了原来的SizedBox间距，使三角形和下拉菜单直接相邻
                  Container(
                    decoration: BoxDecoration(
                      color: widget.dropdownBackgroundColor,
                      borderRadius: BorderRadius.circular(widget.borderRadius),
                      border: Border.all(
                        color: widget.dropdownBorderColor,
                        width: widget.dropdownBorderWidth,
                      ),
                      boxShadow: widget.dropdownBoxShadow,
                    ),
                    constraints: BoxConstraints(
                      maxHeight: widget.maxDropdownHeight,
                    ),
                    child: ListView.builder(
                      shrinkWrap: true,
                      itemCount: widget.deviceList.length,
                      itemBuilder: (context, index) {
                        final deviceName = widget.deviceList[index];
                        // 使用外部传入的isSelected回调判断是否选中
                        final isSelected = widget.isSelected?.call(deviceName) ?? false;

                        return ListTile(
                          // 应用新增的itemPadding参数
                          contentPadding: widget.itemPadding,
                          leading: isSelected
                              ? widget.checkIcon
                              : SizedBox(width: widget.checkIconWidth),
                          title: Text(
                            deviceName,
                            style: isSelected
                                ? widget.selectedItemStyle ?? widget.itemStyle
                                : widget.itemStyle,
                          ),
                          onTap: () {
                            // 不再维护内部状态，完全依赖外部状态管理
                            widget.onSelected?.call(deviceName);
                            _removeOverlay();
                          },
                        );
                      },
                    ),
                  ),
                ],
              ),
            ),
          ),
        );
      },
    );

    Overlay.of(context).insert(_overlayEntry!);
  }

  void _removeOverlay() {
    _overlayEntry?.remove();
    _overlayEntry = null;
  }

  @override
  Widget build(BuildContext context) {
    return CompositedTransformTarget(
      link: _layerLink,
      child: GestureDetector(
        onTap: () {
          if (_overlayEntry == null) {
            _showOverlay();
          } else {
            _removeOverlay();
          }
        },
        child: Container(
          width: widget.width,
          height: widget.height,
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(widget.borderRadius),
            border: Border.all(
              color: widget.borderColor,
              width: widget.borderWidth,
            ),
            color: widget.mainContainerColor,
            boxShadow: widget.boxShadow,
          ),
          padding: widget.padding,
          child: Row(
            mainAxisAlignment: _getMainAxisAlignment(),
            children: [
              Padding(
                padding: widget.titlePadding,
                child: Text(
                  // 使用外部传入的标题，而不是内部状态
                  widget.title,
                  style: widget.titleStyle ?? const TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.w500,
                  ),
                ),
              ),
              widget.arrowIcon,
            ],
          ),
        ),
      ),
    );
  }
}

// 三角形绘制器 - 修改以支持选择性绘制边框
class TrianglePainter extends CustomPainter {
  final Color color;
  final Color borderColor;
  final double borderWidth;
  final bool drawBottomBorder; // 新增参数，控制是否绘制底部边框

  TrianglePainter({
    required this.color,
    required this.borderColor,
    required this.borderWidth,
    this.drawBottomBorder = true, // 默认绘制所有边框
  });

  @override
  void paint(Canvas canvas, Size size) {
    final path = Path();
    path.moveTo(size.width / 2, 0);
    path.lineTo(0, size.height);
    path.lineTo(size.width, size.height);
    path.close();

    // 绘制填充
    final fillPaint = Paint()
      ..color = color
      ..style = PaintingStyle.fill;
    canvas.drawPath(path, fillPaint);

    // 绘制边框（根据drawBottomBorder决定是否绘制底部边框）
    final borderPaint = Paint()
      ..color = borderColor
      ..style = PaintingStyle.stroke
      ..strokeWidth = borderWidth;

    if (drawBottomBorder) {
      // 绘制完整边框
      canvas.drawPath(path, borderPaint);
    } else {
      // 只绘制左右两边的边框，不绘制底部
      final sidePath = Path();
      sidePath.moveTo(size.width / 2, 0);
      sidePath.lineTo(0, size.height);
      sidePath.moveTo(size.width / 2, 0);
      sidePath.lineTo(size.width, size.height);
      canvas.drawPath(sidePath, borderPaint);
    }
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}
